<?php

namespace backend\modules\wechat\controllers;

use backend\controllers\AdminController;
use common\models\wechat\WechatAccounts;
use common\models\wechat\WechatFansGroups;
use Yii;
use common\models\wechat\WechatFans;
use backend\modules\wechat\models\WechatFansSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * FansController implements the CRUD actions for WechatFans model.
 */
class FansController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all WechatFans models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new WechatFansSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single WechatFans model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new WechatFans model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new WechatFans();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing WechatFans model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $model->setAttributes(['wid'=>1]);
        if ($model->load(Yii::$app->request->post())) {
            if(!empty($model->tagsid)){     //给用户打上标签

                $tagmodel = WechatFansGroups::findOne(['wid'=>WechatAccounts::WID]);
                $data = unserialize($tagmodel->groups);
                foreach ($data['tags'] as $key => $row){
                    if($row['id'] == $model->tagsid){
                        $model->tagsname = $row['name'];
                        break;
                    }
                }

                Yii::$app->wechat->user_tag->batchTagUsers([$model->openid],$model->tagsid);
            }else{      //去掉标签

                if(!empty($model->oldAttributes->tagsid)){
                    $res = Yii::$app->wechat->user_tag->batchUntagUsers([$model->openid],$model->oldAttributes->tagsid);
                }

                $model->tagsname = '';
            }
            if($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            }
            return $this->dialog($this->checkError($model));
        } else {
            $tagmodel = WechatFansGroups::findOne(['wid'=>WechatAccounts::WID]);
            $data = unserialize($tagmodel->groups);

            $model->followtime = date('Y-m-d H:i:s',$model->followtime);
            $model->unfollowtime = date('Y-m-d H:i:s',$model->unfollowtime);
            return $this->render('update', [
                'model' => $model,
                'tags' => array_merge(['id'=>'','name'=>''],$data['tags'])
            ]);
        }
    }

    /**
     * Deletes an existing WechatFans model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the WechatFans model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return WechatFans the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = WechatFans::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
